<?php

require_once('shrine.cacher.php');
require_once('spyc.php');

function ml_get_cache($file,$lang){
	global $ml_cacher;
	if( empty($ml_cacher) ) $ml_cacher = new RCacher();
	
	$file_cached = $ml_cacher->load($file.'|'.$lang,filemtime($file));
	
	return $file_cached;
}
function ml_set_cache($file,$lang,$content){
	global $ml_cacher;
	if( empty($ml_cacher) ) $ml_cacher = new RCacher();
	
	return $ml_cacher->save($file.'|'.$lang,$content);
	
}
function ml_get_language(){
	@session_start();
	if( empty($_SESSION['ml_language']) ){
		global $ML_CONFIG;
		return $ML_CONFIG['DEFAULT_LANGUAGE'];
	}else{
		return $_SESSION['ml_language'];
	}
}
function ml_set_language($lang){
	@session_start();
	$_SESSION['ml_language'] = $lang;
}
function ml_handle_php($file){
	$pair = explode('.',basename($file));
	$ext = $pair[count($pair)-1];
	if($ext != 'php') return null;
	$file_ml = $file . '.ml';
	if( !file_exists($file_ml) ) return ml_original_file($file); 
	$lang = ml_get_language();
	
	$file_cached = ml_get_cache($file,$lang);
	if( $file_cached )  return $file_cached;
	
	$map_locale = spyc_load_file($file_ml);
	if( !array_key_exists($lang,$map_locale) ) return ml_original_file($file);
	
	$content = file_get_contents($file);
	$content = ml_localize($content,$map_locale[$lang]); 

	return ml_set_cache($file,$lang,$content);
}
function ml_original_file($file){
	global $ML_CONFIG;
	$file_cached = ml_get_cache($file,'original');
	if( $file_cached )  return $file_cached;
	
	$content = file_get_contents($file);
	
	if( $ML_CONFIG['ENABLE_PATTERN'] ){
		$content = str_replace($ML_CONFIG['PATTERN_BEGIN'],'',$content);
		$content = str_replace($ML_CONFIG['PATTERN_END'],'',$content);
	}
	if( $ML_CONFIG['ENABLE_TAG'] ){
		$content = str_replace($ML_CONFIG['TAG_BEGIN'],'',$content);
		$content = str_replace($ML_CONFIG['TAG_END'],'',$content);
	}
	
	return ml_set_cache($file,'original',$content);
}
function ml_localize($content,$map_locale){
	global $ML_CONFIG;
	

	if( $ML_CONFIG['ENABLE_PATTERN'] ){
		$list_replace_from = array();
		$list_replace_to = array();
		foreach($map_locale as $k=>$v){
			array_push($list_replace_from,$ML_CONFIG['PATTERN_BEGIN'].$k.$ML_CONFIG['PATTERN_END']);
			array_push($list_replace_to,$v);
		}
		$content = str_replace($list_replace_from,$list_replace_to,$content);
	}
	
	if( $ML_CONFIG['ENABLE_TAG'] ){
		$list_replace_from = array();
		$list_replace_to = array();
		foreach($map_locale as $k=>$v){
			array_push($list_replace_from,$ML_CONFIG['TAG_BEGIN'].$k.$ML_CONFIG['TAG_END']);
			array_push($list_replace_to,$v);
		}
		$content = str_replace($list_replace_from,$list_replace_to,$content);
	}
	return $content;
}

?>